{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "def preprocess(img, imgsize, jitter, random_placing=False):\n",
    "    \"\"\"\n",
    "    Image preprocess for yolo input\n",
    "    Pad the shorter side of the image and resize to (imgsize, imgsize)\n",
    "    Args:\n",
    "        img (numpy.ndarray): input image whose shape is :math:`(H, W, C)`.\n",
    "            Values range from 0 to 255.\n",
    "        imgsize (int): target image size after pre-processing\n",
    "        jitter (float): amplitude of jitter for resizing\n",
    "        random_placing (bool): if True, place the image at random position\n",
    "\n",
    "    Returns:\n",
    "        img (numpy.ndarray): input image whose shape is :math:`(C, imgsize, imgsize)`.\n",
    "            Values range from 0 to 1.\n",
    "        info_img : tuple of h, w, nh, nw, dx, dy.\n",
    "            h, w (int): original shape of the image\n",
    "            nh, nw (int): shape of the resized image without padding\n",
    "            dx, dy (int): pad size\n",
    "    \"\"\"\n",
    "    h, w, _ = img.shape\n",
    "    img = img[:, :, ::-1]\n",
    "    assert img is not None\n",
    "    #尺寸大小的随机抖动，jitter越大，长宽的的变化越大\n",
    "    if jitter > 0:\n",
    "        # add jitter\n",
    "        dw = jitter * w\n",
    "        dh = jitter * h\n",
    "        new_ar = (w + np.random.uniform(low=-dw, high=dw))\\\n",
    "                 / (h + np.random.uniform(low=-dh, high=dh))\n",
    "    else:\n",
    "        new_ar = w / h\n",
    "\n",
    "    if new_ar < 1:\n",
    "        nh = imgsize\n",
    "        nw = nh * new_ar\n",
    "    else:\n",
    "        nw = imgsize\n",
    "        nh = nw / new_ar\n",
    "    nw, nh = int(nw), int(nh)\n",
    "    #图像填充位置的随机性\n",
    "    if random_placing:\n",
    "        dx = int(np.random.uniform(imgsize - nw))\n",
    "        dy = int(np.random.uniform(imgsize - nh))\n",
    "    else:\n",
    "        dx = (imgsize - nw) // 2\n",
    "        dy = (imgsize - nh) // 2\n",
    "\n",
    "    img = cv2.resize(img, (nw, nh))\n",
    "    sized = np.ones((imgsize, imgsize, 3), dtype=np.uint8) * 127\n",
    "    sized[dy:dy+nh, dx:dx+nw, :] = img\n",
    "\n",
    "    info_img = (h, w, nh, nw, dx, dy)\n",
    "    return sized, info_img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "jitter=0.1\n",
    "andom_placing=True\n",
    "img_size=416"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "img=cv2.imread('data/1.jpg')\n",
    "# print(img.shape)\n",
    "# img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n",
    "# img[:,:,2] = img[:,:,2]+10\n",
    "# img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB)\n",
    "# # cv2.imwrite('img_or.jpg',img)\n",
    "# cv2.imwrite('img_dis3.jpg',img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sized, info_img=preprocess(img, img_size, jitter=jitter,random_placing=andom_placing)\n",
    "# print(sized.shape)\n",
    "# sized=sized[:,:,::-1]\n",
    "# cv2.imshow('imgs',img)\n",
    "# cv2.imshow('img',sized)\n",
    "cv2.waitKey()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def random_distort(img, hue, saturation, exposure):\n",
    "    \"\"\"\n",
    "    perform random distortion in the HSV color space.\n",
    "    Args:\n",
    "        img (numpy.ndarray): input image whose shape is :math:`(H, W, C)`.\n",
    "            Values range from 0 to 255.\n",
    "        hue (float): random distortion parameter.\n",
    "        saturation (float): random distortion parameter.\n",
    "        exposure (float): random distortion parameter.\n",
    "    Returns:\n",
    "        img (numpy.ndarray)\n",
    "    \"\"\"\n",
    "    #hue 调整色彩度，sat 调整对比度， exp调整亮度\n",
    "    dhue = np.random.uniform(low=-hue, high=hue)\n",
    "    dsat = rand_scale(saturation)\n",
    "    dexp = rand_scale(exposure)\n",
    "\n",
    "    img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n",
    "    img = np.asarray(img, dtype=np.float32) / 255.\n",
    "    img[:, :, 1] *= dsat\n",
    "    img[:, :, 2] *= dexp\n",
    "    H = img[:, :, 0] + dhue\n",
    "\n",
    "    if dhue > 0:\n",
    "        H[H > 1.0] -= 1.0\n",
    "    else:\n",
    "        H[H < 0.0] += 1.0\n",
    "\n",
    "    img[:, :, 0] = H\n",
    "    img = (img * 255).clip(0, 255).astype(np.uint8)\n",
    "    img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB)\n",
    "    img = np.asarray(img, dtype=np.float32)\n",
    "\n",
    "    return img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rand_scale(s):\n",
    "    \"\"\"\n",
    "    calculate \n",
    "    random scaling factor\n",
    "    Args:\n",
    "        s (float): range of the random scale.\n",
    "    Returns:\n",
    "        random scaling factor (float) whose range is\n",
    "        from 1 / s to s .\n",
    "    \"\"\"\n",
    "    scale = np.random.uniform(low=1, high=s)\n",
    "    if np.random.rand() > 0.5:\n",
    "        return scale\n",
    "    return 1 / scale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "hue=0.2\n",
    "saturation=1.5\n",
    "exposure=1.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "img2 = random_distort(sized, hue, saturation, exposure)\n",
    "sized=sized[:,:,::-1]\n",
    "# img2 = cv2.cvtColor(img2, cv2.COLOR_HSV2RGB)\n",
    "img2=img2[:,:,::-1]\n",
    "cv2.imwrite('img_or.jpg',img)\n",
    "cv2.imwrite('img_dis.jpg',img2)\n",
    "# cv2.waitKey()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
